package com.excel.manager.excel;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import com.excel.manager.annotation.Columns;

/**
 * @author ravi
 * */
public class AppendToExcel<T> {

    private Map<Object, Integer> excelHeaderMap;
    private Map<String, Field> fieldMapping = new HashMap<String, Field>();

    public void appendToExcel(Sheet sheet, Set<T> list, Class<T> clazz, int headerRow) throws ClassNotFoundException, IllegalArgumentException,
            IllegalAccessException {

        excelHeaderMap = Utilities.createHeaderMap(sheet, headerRow);
        Field[] fields = clazz.getFields();

        for (Field field : fields) {
            Columns column = field.getAnnotation(Columns.class);
            if (column == null || column.value() == null || column.value().trim().equals("")) {
                continue;
            }
            fieldMapping.put(column.value(), field);
        }

        int totalRows = Utilities.getPhysicalNumberOfRows(sheet);
        for (T listObject : list) {
            Row row = sheet.createRow(totalRows++);

            for (Map.Entry<String, Field> entry : fieldMapping.entrySet()) {
                int cellCount = excelHeaderMap.get(entry.getKey());
                Cell cell = row.createCell(cellCount);
                Field cellField = entry.getValue();
                Object cellValue = cellField.get(listObject);

                if (cellValue instanceof Double) {
                    cell.setCellValue((Double) cellValue);

                } else if (cellValue instanceof String) {
                    cell.setCellValue((String) cellValue);

                } else if (cellValue instanceof Date) {
                    cell.setCellValue((Date) cellValue);

                } else if (cellValue instanceof Boolean) {
                    cell.setCellValue((Boolean) cellValue);
                }
            }
        }
    }
}
